<?php

namespace CommonBundle\Service;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use CommonBundle\Entity\Album;
use CommonBundle\Entity\Region;
use CommonBundle\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;

class SmsService
{
    /** @var ContainerInterface */
    private $container;
    /** @var \Doctrine\ORM\EntityManager|object */
    private $em;

    function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->em = $container->get('doctrine.orm.entity_manager');
    }

    /**
     * @param $mobile
     * @param $code
     * @return string
     * @throws ClientException
     */
    public function sendCode($mobile, $code)
    {
        $config = $this->container->getParameter('aliyun.sms.verify_code');
        $param = [
            'code' => $code
        ];

        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessSecret'])
            ->regionId($config['regionId'])
            ->asGlobalClient();

        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => $config['SignName'],
                        'TemplateCode' => $config['TemplateCode'],
                        'TemplateParam' => json_encode($param)
                    ],
                ])
                ->request();
        } catch (ClientException $e) {
            //dump($e->getErrorMessage() . PHP_EOL);
            return false;
        } catch (ServerException $e) {
            //dump($e->getErrorMessage() . PHP_EOL);
            return false;
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }
}
